package com.example.turncardapp

import android.graphics.Bitmap
import android.os.Bundle
import android.util.Base64
import android.util.Patterns
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.RadioGroup
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.ByteArrayOutputStream

class MainActivity2 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main2)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // Find views
        val etName = findViewById<EditText>(R.id.editTextText)
        val etStudent = findViewById<EditText>(R.id.editTextText2)
        val etPhone = findViewById<EditText>(R.id.editTextText3)
        val etEmail = findViewById<EditText>(R.id.editTextText4)
        val rgGender = findViewById<RadioGroup>(R.id.radioGroupGender)
        val cb1 = findViewById<CheckBox>(R.id.checkBox)
        val cb2 = findViewById<CheckBox>(R.id.checkBox2)
        val cb3 = findViewById<CheckBox>(R.id.checkBox3)
        val cb4 = findViewById<CheckBox>(R.id.checkBox4)
        val btnSave = findViewById<Button>(R.id.btnSave)
        val btnCancel = findViewById<Button>(R.id.btnCancel)
        val imageView = findViewById<ImageView>(R.id.imageView)

        // State for avatar bytes (latest captured)
        var avatarBytes: ByteArray? = null

        // Camera preview launcher (returns a small Bitmap)
        val takePicture = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) { bitmap: Bitmap? ->
            bitmap?.let {
                // show preview
                imageView.setImageBitmap(it)
                // compress to JPEG byte array
                val baos = ByteArrayOutputStream()
                it.compress(Bitmap.CompressFormat.JPEG, 80, baos)
                val bytes = baos.toByteArray()
                avatarBytes = bytes
                // also save base64 into prefs for persistence
                val encoded = Base64.encodeToString(bytes, Base64.DEFAULT)
                val prefs = getSharedPreferences("profile", MODE_PRIVATE)
                prefs.edit().putString("avatar_base64", encoded).apply()
            }
        }

        // Image click starts camera preview
        imageView.setOnClickListener {
            takePicture.launch(null)
        }

        // Also wire the take-photo button (so user sees a clear affordance)
        val takePhotoBtn = findViewById<Button>(R.id.buttonTakePhoto)
        takePhotoBtn.setOnClickListener {
            takePicture.launch(null)
        }

        // Load existing values (optional)
        val prefs = getSharedPreferences("profile", MODE_PRIVATE)
        etName.setText(prefs.getString("name", ""))
        etStudent.setText(prefs.getString("student", ""))
        etPhone.setText(prefs.getString("phone", ""))
        etEmail.setText(prefs.getString("email", ""))
        when (prefs.getString("gender", "")) {
            "male" -> rgGender.check(R.id.radioButton)
            "female" -> rgGender.check(R.id.radioButton2)
        }
        val hobbies = prefs.getString("hobbies", "") ?: ""
        cb1.isChecked = hobbies.contains("放屁")
        cb2.isChecked = hobbies.contains("吹牛")
        cb3.isChecked = hobbies.contains("唱歌")
        cb4.isChecked = hobbies.contains("跳舞")

        // If there is saved avatar base64, decode and display
        prefs.getString("avatar_base64", null)?.let { encoded ->
            try {
                val decoded = Base64.decode(encoded, Base64.DEFAULT)
                val bmp = android.graphics.BitmapFactory.decodeByteArray(decoded, 0, decoded.size)
                imageView.setImageBitmap(bmp)
                avatarBytes = decoded
            } catch (e: Exception) {
                // ignore decode errors
            }
        }

        btnSave.setOnClickListener {
            // validation
            val name = etName.text.toString().trim()
            if (name.isEmpty()) {
                etName.error = "请输入姓名"
                etName.requestFocus()
                return@setOnClickListener
            }
            val student = etStudent.text.toString().trim()
            if (student.isEmpty()) {
                etStudent.error = "请输入学号"
                etStudent.requestFocus()
                return@setOnClickListener
            }
            val phone = etPhone.text.toString().trim()
            if (phone.isNotEmpty() && phone.length < 6) {
                etPhone.error = "请输入有效的电话号码"
                etPhone.requestFocus()
                return@setOnClickListener
            }
            val email = etEmail.text.toString().trim()
            if (email.isNotEmpty() && !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                etEmail.error = "请输入有效的邮箱地址"
                etEmail.requestFocus()
                return@setOnClickListener
            }

            val gender = when (rgGender.checkedRadioButtonId) {
                R.id.radioButton -> "male"
                R.id.radioButton2 -> "female"
                else -> ""
            }
            val hobbyList = ArrayList<String>()
            if (cb1.isChecked) hobbyList.add(getString(R.string.hobby_1))
            if (cb2.isChecked) hobbyList.add(getString(R.string.hobby_2))
            if (cb3.isChecked) hobbyList.add(getString(R.string.hobby_3))
            if (cb4.isChecked) hobbyList.add(getString(R.string.hobby_4))
            val hobbiesJoined = hobbyList.joinToString(",")

            // Save to SharedPreferences
            prefs.edit().apply {
                putString("name", name)
                putString("student", student)
                putString("phone", phone)
                putString("email", email)
                putString("gender", gender)
                putString("hobbies", hobbiesJoined)
                apply()
            }

            // Prepare result intent to pass data back to calling activity
            val resultIntent = android.content.Intent().apply {
                putExtra("name", name)
                putExtra("student", student)
                putExtra("phone", phone)
                putExtra("email", email)
                putExtra("gender", gender)
                putStringArrayListExtra("hobbies_list", hobbyList)
                putExtra("hobbies", hobbiesJoined)
                avatarBytes?.let { putExtra("avatar_bytes", it) }
            }
            setResult(RESULT_OK, resultIntent)
            finish()
        }

        btnCancel.setOnClickListener {
            finish()
        }
    }
}